import { BarcodeOutlined, LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Checkbox, Col, Form, Input, Row, message } from 'antd';
import { useEffect, useState } from 'react';
import ReactCanvasNest from 'react-canvas-nest';

import adminAPI from '@/services/admin';

import styles from './index.module.css';

const Login = () => {
  const [loginInfo, setLoginInfo] = useState({
    loginId: '',
    loginPwd: '',
    captcha: '',
    remember: true,
  });
  const [captcha, setCaptcha] = useState(null);
  const [messageApi, contextHolder] = message.useMessage();

  useEffect(() => {
    captchaClickHandle();
  }, []);

  const captchaClickHandle = async () => {
    const resp = await adminAPI.getCaptcha();
    setCaptcha(resp);
  };

  const updateInfo = (val, key) => {
    const newInfo = { ...loginInfo };
    newInfo[key] = val;
    setLoginInfo(newInfo);
  };

  const onFinish = async () => {
    const resp = await adminAPI.login(loginInfo);
    console.log(resp);
    // 接口返回，有三种状态：
    // 1.验证码错误 {code: 406, msg: '验证码错误', data: null}
    // 2.账号密码错误 {code: 0, msg: '', data: {data:null}}
    // 3.账号密码正确，验证码正确
    if (resp.data) {
      const adminInfo = resp.data;
      if (adminInfo.data) {
        // 账号信息正确
        if (adminInfo.data.enabled) {
          // 登录成功
          localStorage.setItem('adminToken', adminInfo.token);
          // 跳转到首页
          location.href = '/';
        } else {
          captchaClickHandle();
          messageApi.open({
            type: 'warning',
            content: '账号已禁用，请联系管理员',
          });
        }
      } else {
        // 账号密码不正确
        captchaClickHandle();
        messageApi.open({
          type: 'error',
          content: '账号密码错误',
        });
      }
    } else {
      // 验证码错误
      captchaClickHandle();
      messageApi.open({
        type: 'error',
        content: resp.msg,
      });
    }
  };
  return (
    <div>
      <ReactCanvasNest
        className="canvasNest"
        config={{ pointColor: ' 255, 0, 0 ' }}
        count={66}
        style={{ zIndex: 99 }}
      />
      <div className={styles.container}>
        <h1>coder station 后台管理系统</h1>
        <Form
          name="normal_login"
          className="login-form"
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
        >
          {/* 输入账号 */}
          <Form.Item
            name="username"
            rules={[
              {
                required: true,
                message: '请输入账号',
              },
            ]}
          >
            <Input
              prefix={<UserOutlined className="site-form-item-icon" />}
              placeholder="请输入账号"
              value={loginInfo.loginId}
              onChange={(e) => updateInfo(e.target.value, 'loginId')}
            />
          </Form.Item>

          {/* 输入密码 */}
          <Form.Item
            name="password"
            rules={[
              {
                required: true,
                message: '请输入密码',
              },
            ]}
          >
            <Input
              prefix={<LockOutlined className="site-form-item-icon" />}
              type="password"
              placeholder="请输入密码"
              value={loginInfo.loginPwd}
              onChange={(e) => updateInfo(e.target.value, 'loginPwd')}
            />
          </Form.Item>

          {/* 验证码 */}
          <Form.Item
            name="captcha"
            rules={[
              {
                required: true,
                message: '请输入验证码',
              },
            ]}
          >
            <Row align="middle">
              <Col span={16}>
                <Input
                  prefix={<BarcodeOutlined className="site-form-item-icon" />}
                  placeholder="请输入验证码"
                  value={loginInfo.captcha}
                  onChange={(e) => updateInfo(e.target.value, 'captcha')}
                />
              </Col>
              <Col span={6}>
                <div
                  className={styles.captchaImg}
                  onClick={captchaClickHandle}
                  dangerouslySetInnerHTML={{ __html: captcha }}
                ></div>
              </Col>
            </Row>
          </Form.Item>

          <Form.Item name="remember" className={styles.remember}>
            <Checkbox
              checked={loginInfo.remember}
              onChange={(e) => updateInfo(e.target.checked, 'remember')}
            >
              7天免登录
            </Checkbox>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              className={styles.loginBtn}
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
      {contextHolder}
    </div>
  );
};

export default Login;
